﻿namespace IntegrationTests.ValueConversionTests
{
    using System;
    using System.Linq;
    using DirectoryServicesProtocolsExtensions.LdapConnection;
    using DirectoryServicesProtocolsExtensions.SearchRequest;

    using Microsoft.VisualStudio.TestTools.UnitTesting;

    [TestClass]
    public class StringEncodedGenerilizedDateTime : SemanticValueConversionTest
    {
        [TestMethod]
        public void StringEncodedGenerilizedDateTimeTest()
        {
            // Get LastLogonTimeStamp via PowerShell
            const string dnToTestAgainst = "CN=Administrator,CN=Users,DC=fabrikam,DC=com";
            const string attributeToTestAgainst = "createTimeStamp";
            const string scriptText = "Get-ADObject -identity " +
                                      "'" + dnToTestAgainst + "'" +
                                      " -properties " + attributeToTestAgainst +
                                      " | select -expandproperty " + attributeToTestAgainst;
            var valueAquiredByPowerShell = (DateTime)ExecutePowerShellScript(scriptText)[0].BaseObject;
            Assert.IsNotNull(valueAquiredByPowerShell);

            // Get createTimeStamp via code under test
            var metaMapping = LdapConnection.GetAttributeMetaData(attributeToTestAgainst, LdapMetaMapFactory);
            var ldapQueryPropertiesContainer = new MockFabrikamActiveDirectoryQueryPropertiesContainer
            {
                SearchBaseDN = dnToTestAgainst,
                AttributesToLoad = new[] { attributeToTestAgainst }
            };

            var pagedSearchRequest = new PagedSearchRequest(ldapQueryPropertiesContainer);
            var codeResult = pagedSearchRequest.Execute(LdapConnection).Single()[0];

            var valueAquiredByCodeUnderTest =
                codeResult.Attributes[attributeToTestAgainst].GetValues(metaMapping.RawDotNetTypeEquivalent)[0];
            var semanticallyConvertedByCode =
                metaMapping.SemanticValueConversionFunction(valueAquiredByCodeUnderTest);

            // Since PowerShell automatically adjusts time to local time, convert value aquired by PowerShell to UTC
            Assert.IsTrue(DateTime.Compare(
                TrimMilliseconds(valueAquiredByPowerShell.ToUniversalTime()),
                TrimMilliseconds((DateTime)semanticallyConvertedByCode)) == 0);
        }
    }
}
